import operate from '../common/operate.js'
// import store from '../store/index.js'  
// import CryptoJS from 'crypto-js';
const MD5 = require("./md5.min.js"); //引用加密源码js
// import CryptoJS from '@/uni_modules/aki-cryptojs/js_sdk/aki-cryptojs'

import utils from './utils.js';
export default class Request {

    http(param) {
        // 请求参数
        var url = param.url,
            method = param.method || 'get',
            header = {},
            data = param.data || {},
            token = param.token || "",
            hideLoading = param.hideLoading || false,
            type = param.type || '',
            isJson = param.isJson || false,
            nologin=param.nologin||false

        //拼接完整请求地址
        var requestUrl = type == 'video' ? operate.apis + url : operate.api + url;
        let Authorization = uni.getStorageSync('logintoken') || '';
        //请求方式:GET或POST(POST需配置
       
    
 


    if (method) {
        method = method.toUpperCase(); //小写改为大写
        header['Accept'] = 'application/json'
        //         if (method == "POST" && !isJson) {
        // header['content-type'] = "application/x-www-form-urlencoded"
        //         } else {
        header['content-type'] =isJson? "application/x-www-form-urlencoded": "application/json"
        // }
        if (Authorization) {
            header['X-Access-Token'] = Authorization
        }
        if (Authorization) {
            header['Token'] = Authorization
        }
        // console.log(header)
    }
    if(!Authorization){
            
        if(nologin){
        }else{
            uni.showToast({
                title:'未登录,请先登录',
                icon:'none'
            })
            uni.switchTab({
                url:'/pages/vote/index'
            })
            return
        }
       
        
    }
    //加载圈
    if (!hideLoading) {
        uni.showLoading({
            title: '加载中...'
        });
    }

    // 返回promise

    return new Promise((resolve, reject) => {
        // 请求
        uni.request({
            url: requestUrl,
            data: data,
            method: method,
            header: header,
            dataType: 'json',
            ignoreCertificate: true,
            success: (res) => {
                
                // 判断 请求api 格式是否正确
                
                if (res.statusCode && res.code != 1) {
                    if (res.statusCode == 401||res.data.code ==1001) {
                        uni.removeStorageSync('logintoken');
                        uni.removeStorageSync('userId')
                        uni.removeStorageSync('userInfo')    
                        uni.removeStorageSync('schoolId')    
                        setTimeout(() => {
                            uni.reLaunch({
                                url: '/pages/login/login'
                            })
                        }, 1000)
                        return;
                    }

                    return;
                }
                // code判断:200成功,不等于200错误
                if (res.code >= 1) {
                    if (res.code != 1) {
                        setTimeout(() => {
                            // uni.showToast({
                            //     title: res.msg,
                            //     icon: 'none',
                            // });
                        }, 30)
                        // console.log(JSON.stringify(res))
                        if (res.code == 400) {
                            // setTimeout(()=>{
                            // 	uni.navigateTo({
                            // 		url:'/pages/business/join'
                            // 	})
                            // },1000)
                        }
                        if (res.code == 1001) {
                            uni.removeStorageSync('logintoken');
                            uni.removeStorageSync('userId')
                            uni.removeStorageSync('userInfo')    
                            uni.removeStorageSync('schoolId')  
                            setTimeout(() => {
                                uni.reLaunch({
                                    url: '/pages/login/login'
                                })
                            }, 1000)
                        }
                        return;
                    }
                } else {
                    // uni.showToast({
                    //     title: res.msg,
                    //     icon: 'none'
                    // });
                    return;
                }
                // 将结果抛出
                resolve(res.data)
            },
            //请求失败
            fail: (e) => {
                console.log(e)
                uni.showToast({
                    title: "" + e.data.msg,
                    icon: 'none'
                });
                resolve(e.data);
            },
            //请求完成
            complete(e) {
                //隐藏加载
                if (!hideLoading) {
                    uni.hideLoading();
                }
                resolve(e.data);
                return;
            }
        })
    })
}
//上传类
upLoadFile(options) {
    // uni.showLoading({
    //     title: '上传中...'
    // });
    let appKey = 'shuangan20200417';
    
    let isFormData = false
    let paramKey = [];
    let sign = '';
   
        sign = sign + appKey
    let header = {
        
    }
    
   
    var localTime2 = parseInt(Date.parse(new Date()) / 1000);
    // let nonce = guid();
    var localTime1 = uni.getStorageSync("localTime1");
    var serverTime = uni.getStorageSync("serverTime");
    var timeStamp = Number(localTime2) - Number(localTime1) + Number(serverTime);
        sign = sign + timeStamp;      
        
        header = {
            "userId": uni.getStorageSync('userId'),
              'Token': uni.getStorageSync('logintoken'),
            'timestamp': timeStamp,
            'sign': MD5(sign).toString(),
            // #ifdef MP
            "Content-Type": "multipart/form-data",
            // #endif
        }

    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: operate.api + '/file/upload',
            filePath: options.filePath,
            name: 'file',
            header:header,

            success: (uploadFileRes) => {
                uni.hideLoading()
                    
                let res = JSON.parse(uploadFileRes.data);
                if (res.code == 0) {
                    resolve(res)
                } else {
                    resolve(res)
                }
            },
            fail: (err) => {
                uni.hideLoading()
                console.log(err)
                uni.showToast({
                    title: '获取失败',
                    icon: "none"
                })
                reject(err)
            }
        })
    })
}
}